package com.eqdd.yiqidian.ui.gongneng.kehu.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.SearchCoolRefreshRecyclerViewFragmentCustom;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.SaleChanceListResultBean;
import com.eqdd.yiqidian.bean.rebuild.ZhangPageResultBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.gongneng.kehu.SaleChanceInfoActivity;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.SwipeUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import org.reactivestreams.Publisher;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * Created by lvzhihao on 17-5-24.
 */

public class SaleChanceFragment extends BaseFragment {
    SearchCoolRefreshRecyclerViewFragmentCustom dataBinding;
    private SlimAdapterEx<SaleChanceListResultBean> slimAdapterEx;
    private String cusid;
    private String clientName;
    private int pageNum;
    private MVCCoolHelper<List<SaleChanceListResultBean>> mvcHelper;
    private ModelRx2DataSource<SaleChanceListResultBean> dataSource;


    @Override
    protected void setView() {

    }

    @Override
    public void onResume() {
        dataBinding.floatingSearchView.setQueryTextSize(18);
        super.onResume();
    }

    @Override
    public void loadData() {
    }

    @Override
    protected void initData() {
        if (slimAdapterEx == null) {
            dataBinding.floatingSearchView.setSearchHint("销售机会搜索");

            cusid = getArguments().getString("cusid");
            clientName = getArguments().getString(Config.CLIENT_NAME);
            SwipeUtil.openSwipe(getActivity(), dataBinding.recyclerView, (menuBridge, pos) -> {
                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.KEHU_DELETE_SALE_CHANGE)
                        .params("owner", GreenDaoUtil.getUser().getGuid())
                        .params("saleschanceid", slimAdapterEx.getDataItem(pos).getId())
                        .execute(new DialogCallBack<HttpResult>((BaseActivity) getActivity()) {
                            @Override
                            public void onSuccess(Response<HttpResult> response) {
                                HttpResult httpResult = response.body();
                                ToastUtil.showShort(httpResult.getMsg());
                                if (httpResult.getStatus() == 200) {
                                    menuBridge.closeMenu();
                                    slimAdapterEx.getData().remove(pos);
                                    slimAdapterEx.notifyItemRemoved(pos);
                                }
                            }
                        });
            });
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_03, new SlimInjector<SaleChanceListResultBean>() {
                @Override
                public void onInject(SaleChanceListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_right_center_content, data.getContactsName())
                            .text(R.id.tv_upper_left_content, data.getChanceName())
                            .text(R.id.tv_down_left_content, data.getChanceClassify());
                }
            }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
            dataBinding.recyclerView.setSwipeItemClickListener((itemView, position) -> {
                Intent intent = new Intent(getActivity(), SaleChanceInfoActivity.class);
                intent.putExtra("bean", slimAdapterEx.getDataItem(position));
                intent.putExtra(Config.CLIENT_NAME, clientName);
                intent.putExtra("cusid", cusid);
                getActivity().startActivityForResult(intent, position);
            });
            dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                    return OkGo.<ZhangPageResultBean<List<SaleChanceListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.SALE_CHANGE_LIST)
                            .params("page", pageNum)
                            .params("getpeople", 0)
                            .params("owner", AppConstent.user.getGuid())
                            .params("comid", AppConstent.user.getCompanyId())
                            .params("cusid", cusid)
                            .converter(new JsonConverter<ZhangPageResultBean<List<SaleChanceListResultBean>>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<ZhangPageResultBean<List<SaleChanceListResultBean>>>())
                            .flatMap(new Function<ZhangPageResultBean<List<SaleChanceListResultBean>>, Publisher<List<SaleChanceListResultBean>>>() {
                                @Override
                                public Publisher<List<SaleChanceListResultBean>> apply(@NonNull ZhangPageResultBean<List<SaleChanceListResultBean>> noticeWraperResultBeanHttpResult) throws Exception {
                                    if (page == 1) {
                                        mvcHelper.setAutoLoadMore(true);
                                    }
                                    pageNum = page == 1 ? 0 : noticeWraperResultBeanHttpResult.getNextpage();
                                    return Flowable.just(noticeWraperResultBeanHttpResult.getItems() == null ? new ArrayList() : noticeWraperResultBeanHttpResult.getItems());
                                }
                            });

                }
            }, 10);
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            mvcHelper.refresh();
            dataBinding.floatingSearchView.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
                @Override
                public void onSuggestionClicked(SearchSuggestion searchSuggestion) {

                }

                @Override
                public void onSearchAction(String currentQuery) {

                    if (!TextUtils.isEmpty(currentQuery)) {
                        search(currentQuery);
                    }
                }
            });
        }
    }

    private void search(String currentQuery) {
        OkGo.<HttpResult<List<SaleChanceListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.SEARCH_HUIFANG_RECORD)
                .params("param", currentQuery)
                .execute(new DialogCallBack<HttpResult<List<SaleChanceListResultBean>>>((BaseActivity) getActivity()) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<SaleChanceListResultBean>>> response) {
                        HttpResult<List<SaleChanceListResultBean>> httpResult = response.body();
                        if (httpResult.getStatus() == 200) {

                            slimAdapterEx.updateData(httpResult.getItems());
                            mvcHelper.setAutoLoadMore(false);
                        }
                    }
                });
    }

//    private void refresh() {
//        OkGo.<HttpResult<List<SaleChanceListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.SALE_CHANGE_LIST)
//                .params("owner", GreenDaoUtil.getUser().getGuid())
//                .params("cusid", cusid)
//                .execute(new DialogCallBack<HttpResult<List<SaleChanceListResultBean>>>((BaseActivity) getActivity()) {
//                    @Override
//                    public void onSuccess(Response<HttpResult<List<SaleChanceListResultBean>>> response) {
//                        HttpResult<List<SaleChanceListResultBean>> httpResult = response.body();
////                        ToastUtil.showShort(httpResult.getMsg());
//                        if (httpResult.getStatus() == 200) {
//                            slimAdapterEx.updateData(httpResult.getItems());
//                        }
//                        dataBinding.coolRefreshView.setRefreshing(false);
//                    }
//                });
//    }

    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_search_cool_recycler_view, null, false);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            if (requestCode == Config.ADD_XIAOSHOU_RECORD) {
                mvcHelper.refresh();
            } else {
                SaleChanceListResultBean bean = (SaleChanceListResultBean) data.getSerializableExtra("bean");
                slimAdapterEx.getData().remove(requestCode);
                slimAdapterEx.getData().add(requestCode, bean);
                slimAdapterEx.notifyItemChanged(requestCode);
            }
        }
    }
}
